package errcode

import (
	"yunj/pkg/yunj/core/enum"
)

// 定义提示码常量
const (
	SUCCESS int = 0

	ERROR int = 500

	NOT_FOUND int = 404

	LOGOUT int = 200

	OVERDUE int = 401

	NO_AUTH int = 403

	TIMEOUT int = 408
)

// 实现EnumInerface接口
type errcode struct {
	enum.Enum[int]
}

// 定义所有常量属性
func (e *errcode) AllConstAttrs() map[int]map[string]any {
	return map[int]map[string]any{
		SUCCESS: {
			"msg": "操作成功",
		},
		ERROR: {
			"msg":        "系统内部异常，稍后重试~",
			"tipsaction": "__BACK__",
		},
		NOT_FOUND: {
			"msg":        "不好意思，您访问的页面不存在~",
			"tipsaction": "__BACK__",
		},
		LOGOUT: {
			"msg":        "您已成功退出平台！",
			"tipsaction": "__LOGIN__",
		},
		OVERDUE: {
			"msg":        "不好意思，您的登录已过期~",
			"tipsaction": "__LOGIN__",
		},
		NO_AUTH: {
			"msg":        "不好意思，您无权限访问...",
			"tipsaction": "__BACK__",
		},
		TIMEOUT: {
			"msg":        "不好意思，您的操作已超时，请重新登录~",
			"tipsaction": "__LOGIN__",
		},
	}
}

func (e *errcode) GetMsg() (res string) {
	msg := e.GetAttr("msg")
	if msg == nil {
		return
	}
	res, _ = enum.ToString(msg)
	return
}

// 获取提示操作项
func (e *errcode) GetTipsAction() (res string) {
	def := "__LOGIN__"
	action := e.GetAttr("tipsaction")
	if action == nil {
		res = def
		return
	}
	res, _ = enum.ToString(action)
	if res == "" {
		res = def
	}
	return
}

// 判断是否为枚举值val
func IsValue(value any) (val int, ok bool) {
	var err error
	val, err = enum.ToInt(value)
	if err != nil {
		return
	}
	allConstAttrs := Enum.AllConstAttrs()
	_, ok = allConstAttrs[val]
	return
}

// instanceCache 存储已经创建的实例
var instanceCache = make(map[int]*errcode)

// 根据value获取枚举
func ByValue(value int) *errcode {
	if instance, exists := instanceCache[value]; exists {
		return instance
	}
	e := &errcode{}
	enum.SetEnumInstance(&e.Enum, e, value)
	instanceCache[value] = e
	return e
}

var Enum *errcode = func() *errcode {
	e := &errcode{}
	enum.SetEnumInstance(&e.Enum, e)
	return e
}()
